﻿using System.Collections.Generic;
using System.Collections.Specialized;
using System.Collections;
using System.IO;
using System.Xml.Serialization;
using System.Xml;
using System;
namespace MCMLXVII.Core.Common.BackEnd.ConfigurationClasses
{
    [Serializable()]
    public class xmlSerializableGenericCollection<T>: IXmlSerializable 
    {

        private HybridDictionary  _HT;
        

        public xmlSerializableGenericCollection()
        {
            _HT = new HybridDictionary();
        }

        public void Add(T value)
        {
            _HT.Add(((iConfigurationItem)value).Name, value);
        }

        public int Count
        {
            get
            {
                return _HT.Count;
            }
        }

        public T this[string key]
        {
            get { return (T)_HT[key]; }
            set { _HT[key] = value; }
        }

        public T this[int key]
        {
            get { return (T)_HT[key]; }
            set { _HT[key] = value; }
        }


        public ICollection GetItems()
        {
            return (ICollection)_HT;
        }

        System.Xml.Schema.XmlSchema IXmlSerializable.GetSchema()
        {
            return null;
        }

        void IXmlSerializable.ReadXml(XmlReader reader)
        {
            reader.Read();
            reader.ReadStartElement(typeof(T).Name+"s");
            while (reader.NodeType != XmlNodeType.EndElement)
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));
                T value = (T)xs.Deserialize(reader);
                if (reader.NodeType == XmlNodeType.EndElement)
                {
                    reader.ReadEndElement();
                    reader.MoveToContent();
                }
                _HT.Add(((iConfigurationItem)value).Name, value);
            }
            reader.ReadEndElement();
        }

        void IXmlSerializable.WriteXml(XmlWriter writer)
        {
            XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); 
            ns.Add( "", "" ); 

            writer.WriteStartElement(typeof(T).Name + "s");
            foreach (T item in _HT.Values)
            {
                XmlSerializer xs = new XmlSerializer(typeof(T));               
                xs.Serialize(writer, item, ns);
            }
            writer.WriteEndElement();
        }


    }
}
